package com.example.zsr.mydownloadmanager;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.zsr.mydownloadmanager.MesInfo.FilesInfo;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static android.content.ContentValues.TAG;

/**
 * Created by zhengshaorui on 2017/2/22.
 */

public class DownloadManager extends Service{

    private ExecutorService mExecutorService = Executors.newFixedThreadPool(5);//固定线程并发数量为5
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        FilesInfo mFilesInfo = (FilesInfo) intent.getSerializableExtra("fileinfo");

        startdownload(mFilesInfo.getFileUrl(),mFilesInfo.getFileDir(),mFilesInfo.getFileName(),
                mFilesInfo.getThreadcount(),mFilesInfo.getPriority());

        return super.onStartCommand(intent, flags, startId);

    }


    private void startdownload(String apkUrl, String fileDir, String filename, int threadcount
            , int priority) {

        File dir  = new File(fileDir);
        if (!dir.exists()){
            dir.mkdir();
        }

        String filepath =  filename;

        downloadManager downloadManager = new downloadManager(apkUrl,dir,filepath,threadcount,priority);
        mExecutorService.execute(downloadManager);

    }

    class downloadManager extends  Thread{
        String apkurl,filepath;
        int threadcount,priority;
        int blocksize; //每个线程需要下载的区域
        File dir;

        public downloadManager(String apkUrl,File dir, String filepath, int threadcount, int priority) {
            this.apkurl = apkUrl;
            this.filepath = filepath;
            this.threadcount = threadcount;
            this.priority = priority;
            this.dir = dir;
        }

        @Override
        public void run() {

            HttpURLConnection con = null;
            try {
                DownloadTask[]  mDownloadTasks = new DownloadTask[threadcount];
                URL url = new URL(this.apkurl);
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setReadTimeout(5000);
                con.setConnectTimeout(5000);

                int filesize = con.getContentLength(); //获取文件总长度

                if (filesize <= 0){
                    Log.d(TAG, "文件获取失败");
                    return;
                }
                //每一个线程要下载的大小
                blocksize = filesize%threadcount == 0? filesize/threadcount : filesize/threadcount+1;

                Log.d(TAG, "filesize: "+filesize+" blocksize: "+blocksize);

                File file = new File(this.filepath);

                for (int i = 0; i < mDownloadTasks.length; i++) {
                    mDownloadTasks[i] = new DownloadTask(url,dir,filepath,blocksize,
                            i,threadcount,filesize);
                   // mDownloadTasks[i].start();
                    mExecutorService.execute(mDownloadTasks[i]);
                }

                boolean isfinished = false;
                int filelength = 0;
                while(!isfinished){
                    isfinished = true;
                    filelength = 0;
                    for (int i = 0; i < mDownloadTasks.length; i++) {
                        if (!mDownloadTasks[i].isCompleted()){
                            isfinished = false;
                        }else{
                            filelength += mDownloadTasks[i].getDownloadLength();
                        }
                    }
                }
                Log.d(TAG, "finished: "+filelength+" "+filesize);




            } catch (Exception e) {
                e.printStackTrace();
            }

            super.run();
        }
    }
}
